package com.zqxx.examine.portal.controller.action;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zqxx.examine.model.exam.Message;
import com.zqxx.examine.model.training.UserTrainingHistory;
import com.zqxx.examine.portal.security.UserInfo;
import com.zqxx.examine.portal.service.TrainingService;

@Controller
public class TrainingAction
{
  @Autowired
  private TrainingService trainingService;
  
  @RequestMapping(value={"student/set-training-hist"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
  @ResponseBody
  public Message setTrainingHist(@RequestBody UserTrainingHistory history)
  {
    UserInfo userInfo = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    Date now = new Date();
    history.setUserId(userInfo.getUserid());
    history.setLastStateTime(now);
    Message msg = new Message();
    try
    {
      UserTrainingHistory historyOri = this.trainingService.getTrainingHistBySectionId(history.getSectionId(), userInfo.getUserid());
      if (historyOri != null)
      {
        history.setStartTime(historyOri.getStartTime());
        history.setUserTrainingDetail(historyOri.getUserTrainingDetail());
      }
      else
      {
        history.setStartTime(now);
      }
      this.trainingService.setUserTrainingHistory(history);
    }
    catch (Exception e)
    {
      msg.setResult(e.getClass().getName());
      e.printStackTrace();
    }
    return msg;
  }
}

